import React, { useState, useRef, useEffect } from 'react';
import { Modal, Button, Space, message } from 'antd';
import DraggableTable from '@/components/DraggableTable';
import DataReleaseModal from '@/components/DataReleaseModal';

const ReleaseListModal = ({
  visible,
  onClose,
  pendingReleaseList,
  setPendingReleaseList,
  tableData,
  columns,
  fetchTableData
}) => {
  const [releaseType, setReleaseType] = useState(1);
  const [releaseInnerModalOpen, setReleaseInnerModalOpen] = useState(false);
  const releaseTableRef = useRef();

  // 删除发布列表某一行
  const handleDeleteRow = (record) => {
    setPendingReleaseList(prev => prev.filter(item => !((item.product_id || item.key) === (record.product_id || record.key) && item.data_type === record.data_type)));
  };

  // 生成带删除按钮的列
  const getReleaseListColumns = (baseColumns) => {
    const filtered = (baseColumns || []).filter(col => 
      col.key !== 'action' && 
      col.dataIndex !== 'action' && 
      col.key !== 'delete'
    );
    return [
      ...filtered,
      {
        title: '操作',
        key: 'delete',
        width: 60,
        fixed: 'right',
        align: 'center' as const,
        render: (_, record) => (
          <Button danger size="small" onClick={() => handleDeleteRow(record)}>
            删除
          </Button>
        )
      }
    ];
  };

  // 拖拽列
  const [localColumns, setLocalColumns] = useState(() => getReleaseListColumns(columns));
  useEffect(() => {
    setLocalColumns(getReleaseListColumns(columns));
  }, [columns]);
  const handleColumnsChange = (cols) => {
    // 过滤掉操作列，只保留原始列
    const filteredCols = cols.filter(col => col.key !== 'delete');
    setLocalColumns(getReleaseListColumns(filteredCols));
  };

  // 打开内部发布弹窗
  const handleReleaseFromList = (type) => {
    if (pendingReleaseList.length === 0) {
      message.warning('发布列表为空');
      return;
    }
    setReleaseType(type);
    setReleaseInnerModalOpen(true);
  };

  // 关闭内部发布弹窗
  const handleCloseReleaseInnerModal = () => {
    setReleaseInnerModalOpen(false);
    setReleaseType(0);
    // 不要在这里调用onClose或清空列表
  };

  useEffect(() => {
    if (visible) {
      setTimeout(() => {
        const tableBody = releaseTableRef.current?.querySelector('.ant-table-body');
        if (tableBody) {
          tableBody.style.height = 'calc(100vh - 285px)';
          tableBody.style.maxHeight = 'calc(100vh - 285px)';
          tableBody.style.overflowY = 'scroll';
        }
      }, 0);
    }
  }, [visible, pendingReleaseList.length]);

  return (
    <Modal
      title="发布列表"
      open={visible}
      onCancel={onClose}
      footer={null}
      width={1100}
    >
      {pendingReleaseList.length === 0 ? (
        <div style={{ height: 'calc(100vh - 250px)', display: 'flex', alignItems: 'center', justifyContent: 'center', textAlign: 'center', color: '#888' }}>暂无待发布数据</div>
      ) : (
        <>
          <div
            ref={releaseTableRef}
            style={{ height: 'calc(100vh - 250px)', overflow: 'auto', marginBottom: 16 }}
            className="release-table-scroll"
          >
            <DraggableTable
              columns={getReleaseListColumns(localColumns)}
              onColumnsChange={handleColumnsChange}
              dataSource={pendingReleaseList}
              size="small"
              bordered
              pagination={false}
              scroll={{ x: 'max-content', y: 'calc(100vh - 285px)' }}
              rowClassName={(_, index) => (index % 2 === 0 ? 'zebra-row-odd' : 'zebra-row-even')}
              style={{ fontSize: 13 }}
            />
          </div>
          <Space>
            <Button type="primary" onClick={() => handleReleaseFromList(1)}>
              立即发布
            </Button>
            <Button type="primary" onClick={() => handleReleaseFromList(2)}>
              定时发布
            </Button>
            <Button onClick={() => {
              setPendingReleaseList([]);
              onClose();
            }} danger>
              清空列表
            </Button>
          </Space>
        </>
      )}
      <DataReleaseModal
        open={releaseInnerModalOpen}
        onCancel={handleCloseReleaseInnerModal}
        releaseType={releaseType}
        files={pendingReleaseList.map((item) => ({
          data_type: item.data_type,
          product_id: item.product_id || item.key
        }))}
        onSuccess={() => {
          setReleaseInnerModalOpen(false);
          setReleaseType(0);
          setTimeout(() => {
            onClose();
            setPendingReleaseList([]);
            fetchTableData && fetchTableData();
          }, 300);
        }}
      />
    </Modal>
  );
};

export default ReleaseListModal; 